<?php
/**
 * 验收记录Service
 */

declare (strict_types = 1);

namespace app\school\service;

use app\common\model\Brand;
use app\common\model\Check;
use app\common\model\Spec;
use app\common\model\Type;
use app\school\exception\ApiServiceException;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

class CheckService extends ApiBaseService {
	protected Check $model;

	public function __construct() {
		$this->model = new Check();
	}

	/**
	 * 列表
	 * @param $param
	 * @param $page
	 * @param $limit
	 * @return array
	 * @throws ApiServiceException
	 */
	public function getList($param, $page, $limit) {
		try {
			$field = 'id,school_id,order_id,send_time,create_time,status';
			$data = $this->model
				->with(['school', 'order', 'user'])
				->scope('ApiWhere', $param)
				->paginate([
					'list_rows' => $limit,
					'page' => $page,
				])
				->each(function ($item, $key) {

					$detail = $item['detail'];
					foreach ($item['detail'] as $key => $value) {
						$detail[$key]['type'] = Type::where('id', $value['type_id'])->find();
						//$detail[$key]['menu'] = Menu::where('id', $value['menu_id'])->find();

						$detail[$key]['brand'] = Brand::where('id', $value['brand_id'])->find();

						$detail[$key]['spec'] = Spec::where('id', $value['spec_id'])->find();

					}
					$item['detail'] = $detail;
					//$item['menu']=Menu::where('id',$item)
					return $item;

				});

		} catch (DataNotFoundException | ModelNotFoundException $e) {
			$data = [];
		} catch (DbException $e) {
			throw new ApiServiceException('查询列表失败，信息' . $e->getMessage());
		}

		return $data;
	}

	/**
	 * 添加
	 * @param $param
	 * @return bool
	 */
	public function createData($param): bool {
		$result = $this->model::create($param);
		return (bool) $result;
	}

	/**
	 * 数据详情
	 * @param $id
	 * @return array
	 * @throws ApiServiceException
	 */
	public function getDataInfo($id): array {
		$data = $this->model->where('id', '=', $id)->findOrEmpty();
		if ($data->isEmpty()) {
			throw new ApiServiceException('数据不存在');
		}
		return $data->toArray();
	}

	/**
	 * 修改
	 * @param $id
	 * @param $param
	 * @return bool
	 * @throws ApiServiceException
	 */
	public function updateData($id, $param): bool {
		$data = $this->model->where('id', '=', $id)->findOrEmpty();
		if ($data->isEmpty()) {
			throw new ApiServiceException('数据不存在');
		}
		$result = $data->save($param);

		if (!$result) {
			throw new ApiServiceException('更新失败');
		}

		return true;
	}

	/**
	 * 删除
	 * @param mixed $id
	 * @return bool
	 * @throws ApiServiceException
	 */
	public function deleteData($id): bool {
		$result = $this->model::destroy(function ($query) use ($id) {
			$query->whereIn('id', $id);
		});

		if (!$result) {
			throw new ApiServiceException('更新失败');
		}

		return true;
	}

}
